package com.ken.common.auth.permission;

import com.ken.ability.auth.protocol.security.AuthPowerDetails;
import com.ken.ability.auth.protocol.security.AuthUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 权限验证器
 */
@Component
@Slf4j
public class AuthPermissionEvaluator implements PermissionEvaluator{

    /**
     * 权限校验
     * @param authentication
     * @param targetDomainObject
     * @param permission
     * @return
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        if (Objects.isNull(permission)) return false;

        AntPathMatcher antPathMatcher = new AntPathMatcher();

        AuthUserDetails authUser = Optional.ofNullable(authentication)
                .map(authentication1 -> authentication1.getPrincipal())
                .filter(o -> o instanceof AuthUserDetails)
                .map(o -> (AuthUserDetails) o)
                .orElse(new AuthUserDetails());

        List<AuthPowerDetails> powers = authUser.getPowers();
        if (!CollectionUtils.isEmpty(powers)) {
            for (AuthPowerDetails authPower : powers) {
                String powerRest = authPower.getPowerRest();
                if (StringUtils.isEmpty(powerRest)) continue;
                log.debug("[Auth-Permission] - 校验权限 - {}:{}", powerRest, permission);
                boolean result = antPathMatcher.match(powerRest, String.valueOf(permission));
                if (result) {
                    log.debug("[Auth-Permission] - 权限校验通过 - {}", permission);
                    return result;
                }
            }
        }

        log.debug("[Auth-Permission] - 权限校验不通过 - {}", permission);
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
